using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;

namespace Geekeradmin.Filters
{
    /// <summary>
    /// 异步日志记录
    /// </summary>
    public class CustomLogAsyncAction : Attribute, IAsyncActionFilter
    {
        private readonly ILogger<CustomLogAsyncAction> logger;
        public CustomLogAsyncAction(ILogger<CustomLogAsyncAction> logger)
        {
            this.logger = logger;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //在这里判断一下，如果标记的有匿名---可以让这里的逻辑都不执行，直接过去
            if (context.ActionDescriptor.EndpointMetadata.Any(c => c.GetType().Equals(typeof(CustomAllowAnonymous))))
            {
                //支持匿名
                await next();
            }
            else
            {
                var paramsdata = String.Join('&', context.HttpContext.Request.Query.Select(o => { return string.Format("{0}={1}", o.Key, o.Value); }));
                //var paramsdata = context.HttpContext.Request.QueryString.Value;
                var controller = context.HttpContext.GetRouteValue("controller");
                var action = context.HttpContext.GetRouteValue("action");
                ActionExecutedContext executedContext = await next.Invoke();//执行Action
                var result = JsonConvert.SerializeObject(executedContext.Result);
                var info = $"控制器{controller}执行方法{action}的参数是{paramsdata}的结果是{result}";
                //Console.WriteLine(info);
                //this.logger.LogInformation(info);
            }
        }
    }
}
